﻿using System;
using UnityEngine;
using UnityEngine.UI;

namespace GameBoxTools
{
    public class RenderCtrl
    {
        private const int start_Y = -40;
        private const int height = 35;
        public Button RenderBtn;
        public Toggle RenderToggle;
        public Toggle ShowToggle;
        private Action<int> click;
        /// <summary>
        /// 参数1：index，参数2：0渲染并显示 1只渲染不显示 2不渲染不显示
        /// </summary>
        private Action<int, int> callback;

        public RenderCtrl(GameObject _go, Transform _root, int index, bool wrong, Action<int> _click, Action<int, int> call)
        {
            this.callback = call;
            this.click = _click;

            GameObject go = UnityEngine.Object.Instantiate(_go);
            go.SetActive(true);
            go.name = string.Format("R{0}", index + 1);
            go.transform.localPosition = new Vector3(0, start_Y - index * height, 0);
            go.transform.SetParent(_root, false);
            var btn = go.transform.Find("RBtn");
            this.RenderBtn = btn.GetComponent<Button>();
            if (wrong)
            {
                btn.GetComponent<Image>().color = Color.red;
            }
            btn.transform.Find("Text").GetComponent<Text>().text = go.name;
            this.RenderToggle = go.transform.Find("RToggle").GetComponent<Toggle>();
            this.ShowToggle = go.transform.Find("SToggle").GetComponent<Toggle>();

            this.RenderBtn.onClick.AddListener(() =>
            {
                this.click(index);
            });

            this.RenderToggle.onValueChanged.AddListener((flag) =>
            {
                if (flag)
                {
                    this.callback(index, 1);
                }
                else
                {
                    this.callback(index, 2);
                    this.ShowToggle.isOn = flag;
                }
            });

            this.ShowToggle.onValueChanged.AddListener((flag) =>
            {
                if (flag)
                {
                    if (!this.RenderToggle.isOn)
                    {
                        this.ShowToggle.isOn = false;
                    }
                    else
                    {
                        this.callback(index, 0);
                    }
                }
                else
                {
                    if (this.RenderToggle.isOn)
                        this.callback(index, 1);
                }
            });
        }
    }
}